package com.powergisol.gis.util;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FileUnZip {

    private static Logger logger = LoggerFactory.getLogger(FileUnZip.class);

    public static int unzip(String sourceZip,String destDir) throws Exception{
        int i = 0;
        try{
            Project p = new Project();
            Expand e = new Expand();
            e.setProject(p);
            e.setSrc(new File(sourceZip));
            e.setOverwrite(false);
            e.setDest(new File(destDir));
            e.setEncoding("gbk");
            e.execute();
            i = 1;
        }catch(Exception e){
            throw e;
        }
        return i;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("fileUnZip:"+System.currentTimeMillis());
        unzip("E:\\servicedata\\temp\\json\\terrain01.zip","E:\\aa");
        System.out.println(System.currentTimeMillis());
    }

    private static String getFileUrl(List<String> list){
        String url = list.get(0);
        int i=url.length()-url.replace(url, "/").length();
        for (String str:list) {
            int j = str.length()-str.replace(str, "/").length();
            if(i>j){
                url = str;
                i=j;
            }
        }
        return url;
    }


    /**
     * 判断是否存在正确的文件
     * @return
     */
    private static boolean getFileSuffix(File file, String assinSuffixName) throws IOException {
        Boolean flag = false;
        ZipInputStream in = new ZipInputStream(new FileInputStream(file), Charset.forName("gbk"));//charset
        ZipEntry zipFile;
        //循环读取zip中的cvs文件，使用jdk自带就可以，编码格式gbk，
        while ((zipFile=in.getNextEntry())!=null) {
            if (zipFile.isDirectory()){
                continue;
            }
            String fileName = zipFile.getName();
            //检测文件是否存在
            if (fileName != null && fileName.indexOf(".") != -1&&fileName.substring(fileName.lastIndexOf("."),fileName.length()).contains(assinSuffixName)) {
                flag = true;
                break;
            }
        }
        return flag;
    }
    private static List<String> getRightFile(File file, String assinSuffixName) throws IOException {
        List<String> list = new ArrayList<>();
        ZipInputStream in = new ZipInputStream(new FileInputStream(file), Charset.forName("gbk"));//charset
        ZipEntry zipFile;
        //循环读取zip中的cvs文件，使用jdk自带就可以，编码格式gbk，
        while ((zipFile=in.getNextEntry())!=null) {
            if (zipFile.isDirectory()){
                continue;
            }
            String fileName = zipFile.getName();
            //检测文件是否存在
            if (fileName != null && fileName.indexOf(".") != -1&&fileName.substring(fileName.lastIndexOf("."),fileName.length()).contains(assinSuffixName)) {
                list.add(fileName);
            }
        }
        return list;
    }


    public static Result unZipFiles(String dest, String descDir,String assinSuffixName,String name){
        Result result = new Result();
        File zipFile = new File(dest);
        // 检测是否存在目录
        if (!zipFile.getParentFile().exists()) {
            zipFile.getParentFile().mkdirs();
        }
        //判断zip中是否存在相应的文件
        try {
            Boolean flag = getFileSuffix(zipFile,assinSuffixName);
            if(!flag){
                return result.failure(-401,"请上传含有"+assinSuffixName+"格式的文件");
            }
            unzip(zipFile.getAbsolutePath(),descDir);
        } catch (Exception e) {
            e.printStackTrace();
            return result.failure(-402,"解压失败，请重新上传");
        }
        logger.info("解压成功:{}",name);
        return result;
    }
}


